from decimal import Decimal
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import SKU
from order.serializers import PlaceOrderSerializer, PlaceSerializer, OrderCommitSerializer


class PlaceOrderAPIView(APIView):

    # permission_classes = [IsAuthenticated]

    def get(self,request):

        user = request.user

        redis_conn = get_redis_connection("cart")
        sku_id_counts = redis_conn.hgetall("cart_%s" %user.id)

        redis_cart = {}
        for sku_id,count in sku_id_counts.items():
            redis_cart[int(sku_id)] = int(count)

        selected_ids = redis_conn.smembers('cart_selected_%s' % user.id)
        skus = SKU.objects.filter(pk__in=selected_ids)

        for sku in skus:
            sku.count = redis_cart[sku.id]

        # serializer = PlaceOrderSerializer(skus, many=True)


        freight = Decimal('10')
        serializer = PlaceSerializer({
            'skus': skus,
            'freight': freight

        })

        return Response(serializer.data)


class OrderAPIView(APIView):

    def post(self,request):

        data = request.data
        serializer = OrderCommitSerializer(data=data,context={"request":request})

        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)


from order.serializers import CommentSerializer
from rest_framework.generics import CreateAPIView
from order.models import OrderGoods,OrderInfo

class CommentOrderAPIView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self,requset,order_id):

        data = requset.data
        sku = data.get("sku")
        try:
            orders = OrderGoods.objects.get(order = order_id,sku = sku)
        except OrderGoods.DoesNotExist:
            return Response("订单不存在")

        serializer = CommentSerializer(instance=orders,data=data)

        serializer.is_valid(raise_exception=True)
        serializer.save()

        id = OrderInfo.objects.get(order_id=order_id)
        id.status = '5'
        id.save()


        return Response("ok")